import json

from common.util.date_encoder import DateEncoder
from ecs.ecs_cluster import EcsCluster
from ecs.ecs_task import EcsTask


def spider_completed_handler(next_job, event, context):
    """
    handle events only source == 'pt.spider' and detail-type == 'Spider State-change Notification' and detail.state == 'COMPLETED'
    :param next_job:
    :param event:
    :param context:
    :return:
    """
    print("triggered spider_completed_handler: %s" % event)
    job_name = next_job["jobName"]
    job_version = next_job["jobVersion"]
    if job_name:
        print("task name is %s..." % job_name)
        ecsCluster = EcsCluster('ptadmin-automation-ec2')
        ecsTask = EcsTask(task_definition_name=job_name, version=job_version)

        response = ecsCluster.submit_task(ecsTask)
        print("done...response is...")
        print(response)
        return {
            'statusCode': 200,
            'body': json.dumps(response, cls=DateEncoder)
        }
    else:
        print("skipped trigger after flow to step %s..." % job_name)
        return {
            'statusCode': 200,
            'body': json.dumps({"msg": "skipped trigger after flow to step %s..." % job_name})
        }


def emr_completed_handler(next_job, event, context):
    """
    handle events only source == 'aws.emr' and detail-type == 'EMR Step Status Change' and detail.state == 'COMPLETED'
    :param next_job:
    :param event:
    :param context:
    :return:
    """
    print("triggered emr_completed_handler: %s" % event)
    job_name = next_job["jobName"]
    step_name = event['detail']['name']
    if job_name and "Debugging" not in step_name:
        ecsCluster = EcsCluster('ptadmin-automation-ec2')
        ecsTask = EcsTask(task_definition_name=job_name, version='latest')

        response = ecsCluster.submit_task(ecsTask)
        return {
            'statusCode': 200,
            'body': json.dumps(response)
        }
    else:
        print("skipped trigger after flow to step %s..." % step_name)
        return {
            'statusCode': 200,
            'body': json.dumps({"msg": "skipped trigger after flow to step %s..." % step_name})
        }